package crud

import (
	"os"
	"strings"

	"api/system/helper"
)

var cServiceFTempl = `<?php
namespace {{.__NAMESPACE__}};

use app\service\api\BaseService;
use {{.__MODEL__}} as CustomModel;
use app\service\api\MemberServiceFacade;
use {{.__VALIDATE__}}\Add;
use {{.__VALIDATE__}}\Edit;

use think\facade\Db;
use think\Exception;

class {{.__CLASS__}} extends BaseService
{
    private ?CustomModel $model = null;
    private ?int $uid = 0;

    public function init() {
        $this->model = app(CustomModel::class);
        $user = MemberServiceFacade::getUser();
        $this->uid = $user->id ?? 0;
    }

    // 增加 和 编辑 合二为一
    public function doSave(array $param): bool {

        try {
            Db::startTrans();

            if (empty($param)) {
                $this->_E("没有传递任何参数");
            }

            $id = $param['id'] ?? 0;
            $uid = $this->uid;

            if ($id > 0) {      // 编辑
                $validate = new Edit();
                if(!$validate->check($param)){
                    $this->_E($validate->getError());
                }

                $objModel = $this->model->where(['id' => $id, 'user_id' => $uid])->find();
                if (!$objModel) {
                    $this->_E("数据不存在");
                }

                // 判断唯一性
                $cnt = $this->model->where(['user_id' => $uid, 'name' => $param['name']])->whereRaw("id <> {$id}")->count('id');
                if ($cnt > 0) {
                    $this->_E("已经有该数据了，换一个名称");
                }

                foreach ($param as $k => $v) {
                    if (in_array($k, ['id', 'user_id','create_time'])) {
                        continue;
                    }

                    $objModel->$k = $v;
                }

                $flag = $objModel->save();
                if (false === $flag) {
                    $this->_E("保存数据失败");
                }
            } else {        // 添加
                $validate = new Add();
                if(!$validate->check($param)){
                    $this->_E($validate->getError());
                }

                $objModel = $this->model->where(['user_id' => $uid, 'name'=>$param['name']])->find();
                if ($objModel) {
                    $objModel->update_time = date('Y-m-d H:i:s', time());
                    $flag = $objModel->save();
                    if (false === $flag) {
                        $this->_E("保存数据失败");
                    }
                } else {
                    $cnt = $this->model->where(['user_id' => $uid])->count('id');
                    if ($cnt <= 0) {
                        $param['is_default'] = 1;
                    }

                    $param['user_id'] = $uid;
                    $param['create_time'] = date('Y-m-d H:i:s', time());
                    $param['update_time'] = date('Y-m-d H:i:s', time());

                    $lastid = $this->model->insertGetId($param);
                    if (!$lastid) {
                        $this->_E("写入数据失败");
                    }
                }
            }

            Db::commit();
        } catch (Exception $e) {
            $this->setError($e->getMessage());

            Db::rollback();
            return false;
        }

        return true;
    }

    // 获取信息
    public function info(int $id): array {
        $objModel = $this->model->where(['id' => $id, 'user_id' => $this->uid])->find();
        if (!$objModel) {
            return [];
        }

        return $objModel->toArray();
    }

    // 获取列表
    public function list(array $param): array {
        $page = $param['page'] ?? 1;
        $pageSize = $param['page_size'] ?? 10;

        $count = $this->model->where(['user_id' => $this->uid, 'status' => 1])->count();
        $list = $this->model->withoutField('update_time, status')->where(['user_id' => $this->uid, 'status' => 1])->order('id', 'asc')->page($page, $pageSize)->select()->toArray();

        return [
            'count' => $count,
            'list' => $list
        ];
    }

    // 设为默认值
    public function defaults(int $id): bool {

        try {
            Db::startTrans();

            $objModel = $this->model->where(['id' => $id, 'user_id' => $this->uid])->find();
            if (!$objModel) {
                $this->_E("数据不存在");
            }
            $objModel->is_default = 1;
            $flag = $objModel->save();
            if (false === $flag) {
                $this->_E("保存失败");
            }

            $flag = $this->model->where(['user_id' => $this->uid])->whereRaw("id <> {$id}")->save(['is_default' => 0]);
            if (false === $flag) {
                $this->_E("重置默认值失败");
            }

            Db::commit();

            return true;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            Db::rollback();

            return false;
        }
    }

    // 删除数据
    public function delete(int $id): bool {

        try {
            Db::startTrans();

            $objModel = $this->model->where(['id' => $id, 'user_id' => $this->uid])->find();
            if (!$objModel) {
                $this->_E("数据不存在");
            }
            $flag = $objModel->delete();
            if (false === $flag) {
                $this->_E("删除失败");
            }

            Db::commit();

            return true;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            Db::rollback();

            return false;
        }
    }
}`

// 生成控制器
func (g *cGlobal) MakeServices() error {
	inx := strings.LastIndex(g.ServicePath, "\\")
	nName := g.ServicePath[:inx]
	err := os.MkdirAll(nName, os.ModePerm)
	if err != nil {
		return err
	}

	className := ""
	cinx := strings.LastIndex(g.TableName, "_")
	if cinx > 0 {
		lowerClassName := g.TableName[cinx+1:]
		className = helper.UcFirst(lowerClassName)
	} else {
		className = helper.UcFirst(g.TableName)
	}

	m := map[string]string{
		"__NAMESPACE__": g.ServiceNameSpace,
		"__MODEL__":     g.ModelNameSpace + "\\" + className,
		"__VALIDATE__":  g.ValidateNameSpace,
		"__CLASS__":     className,
	}

	fileName := g.ServicePath
	err = TemplateExec(fileName, cServiceFTempl, m)
	if err != nil {
		return err
	}

	return nil
}
